<template>
  <el-row :gutter="20">
    <el-col :lg="6" :md="24" :sm="24" :xs="24" style="height: 100%">
      <el-card class="box-card fix-el-card" shadow="hover">
        <template #header>
          <span> {{ t("account.organizations") }}</span>
          <span>
            <el-button class="button" link @click="handleTreeClearSelect">{{
              t("common.deselect")
            }}</el-button>
            <el-tooltip
              class="box-item"
              effect="dark"
              :content="t('common.refreshButton')"
              placement="top"
            >
              <el-button class="button" link @click="handleCodeRefresh">
                <el-icon :size="18">
                  <ico-svg icon="grid-refresh-line"></ico-svg>
                </el-icon>
              </el-button>
            </el-tooltip>
          </span>
        </template>
        <el-tree
          v-if="state.refresh"
          ref="treeRef"
          node-key="orgId"
          :props="treeProps"
          :load="lazyLoadNode"
          @current-change="onTreeNodeCurrentChange"
          lazy
        />
      </el-card>
    </el-col>
    <el-col :lg="18" :md="24" :sm="24" :xs="24">
      <!-- 查询表单 -->
      <el-form
        ref="formSearchRef"
        label-width="100px"
        :inline="true"
        :model="formSearch"
        class="data-grid-search-form"
      >
        <el-row>
          <el-col :lg="8" :md="12" :sm="12" :xs="24">
            <el-form-item :label="t('account.name')" prop="name">
              <el-input v-model="formSearch.name" clearable> </el-input>
              <el-input type="hidden" v-model="formSearch.orgCode"></el-input>
            </el-form-item>
          </el-col>
          <el-col :lg="8" :md="12" :sm="12" :xs="24">
            <el-form-item :label="t('account.account')" prop="account">
              <el-input v-model="formSearch.account" clearable> </el-input>
            </el-form-item>
          </el-col>
          <el-col :lg="8" :md="12" :sm="12" :xs="24" v-if="searchInputExpland">
            <el-form-item
              :label="t('account.employeeNumber')"
              prop="employeeNumber"
            >
              <el-input v-model="formSearch.employeeNumber" clearable>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :lg="8" :md="12" :sm="12" :xs="24" v-if="searchInputExpland">
            <el-form-item :label="t('account.orgName')" prop="orgName">
              <el-input v-model="formSearch.orgName" clearable> </el-input>
            </el-form-item>
          </el-col>
          <el-col :lg="8" :md="12" :sm="12" :xs="24" v-if="searchInputExpland">
            <el-form-item :label="t('account.status')" prop="status">
              <el-select v-model="formSearch.status" clearable>
                <el-option
                  :label="t('common.statusDisabled')"
                  value="0"
                ></el-option>
                <el-option
                  :label="t('common.statusEnabled')"
                  value="1"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :lg="8" :md="12" :sm="12" :xs="24">
            <el-form-item style="float: right">
              <el-button :icon="Search" type="primary" @click="handleSearch">{{
                t("common.searchButton")
              }}</el-button>
              <el-button :icon="RefreshLeft" @click="handleResetFields">{{
                t("common.resetButton")
              }}</el-button>
              <search-input-expland
                @on-expland-change="(v:boolean)=>{ searchInputExpland=v}"
              ></search-input-expland>
            </el-form-item>
          </el-col>
        </el-row>
        <el-divider style="margin: 0"></el-divider>
      </el-form>

      <data-grid
        ref="dataGridRef"
        id="admin-account-grid"
        row-key="accountId"
        defaultSort="ascending"
        defaultSortBy="account"
        :request="handleLoadGrid"
        :columns="state.columns"
        :buttons="state.buttons"
        @on-row-dblclick="handleRowDblclick"
      >
        <!-- 自定义模板，会替换控件中的 buttonSlot id：button 仅在当前作用域有效 -->
        <template #button-primary="button">
          <el-button type="primary" :icon="Plus" @click="handleAdd">{{
            t("account.newAccountButton")
          }}</el-button>
          <el-button :icon="Edit" @click="handleChangePwd">{{
            t("account.resetPassword")
          }}</el-button>
        </template>
        <!-- 自定义模板，会替换控件中的 tdSlot，模板 account 仅在当前作用域有效 -->
        <template #account="slotProps">
          <el-link type="primary" @click="handleView(slotProps.row)">{{
            slotProps.row.account
          }}</el-link>
        </template>

        <!-- 自定义模板，会替换控件中的 tdSlot，模板 status 仅在当前作用域有效 -->
        <template #status="slotProps">
          <el-switch
            v-model="slotProps.row.status"
            :active-value="1"
            :inactive-value="0"
            @change="handleStateChange($event, slotProps.row)"
          />
        </template>

        <!-- 自定义模板，会替换控件中的 tdSlot，模板 operate 仅在当前作用域有效 -->
        <template #operate="slotProps">
          <el-space :size="8">
            <el-link type="primary" @click="handleLog(slotProps.row)">{{
              t("account.logButton")
            }}</el-link>
            <el-link type="primary" @click="handleEdit(slotProps.row)">{{
              t("common.editButton")
            }}</el-link>
            <el-link
              type="primary"
              :title="slotProps.item.title"
              @click="handleDelete(slotProps.row)"
            >
              {{ t("common.deleteButton") }}
            </el-link>
          </el-space>
        </template>
      </data-grid>
    </el-col>
  </el-row>

  <edit-form ref="editFormRef" @on-submit-success="onSubmitSuccess"></edit-form>
  <view-form ref="viewFormRef" :title="t('account.accountInfo')"></view-form>
  <change-password-form ref="changePasswordFormRef"></change-password-form>
</template>
<script setup lang="ts">
import { reactive, ref } from "vue";
import DataGrid from "@/components/DataGrid.vue";
import EditForm from "./edit.vue";
import ViewForm from "./view.vue";
import ChangePasswordForm from "./change-password.vue";
import SearchInputExpland from "../../../components/SearchInputExpland.vue";
import { Edit, Plus, Search, RefreshLeft } from "@element-plus/icons-vue";
import { ElMessageBox } from "element-plus";
import utils from "../../../utils/utils";
import apiAccount from "../api/account";
import apiOrganization from "../api/organization";
import OrgTreeNode from "../organization/tree-node";
import Node from "element-plus/es/components/tree/src/model/node";
import { useRouter } from "vue-router";
import { useI18n } from "vue-i18n";
const { t } = useI18n({ useScope: "global" });

const router = useRouter();
// 变量必须和属性 ref 的值相同
const formSearchRef = ref();
const dataGridRef = ref();
const editFormRef = ref();
const viewFormRef = ref();
const changePasswordFormRef = ref();
// 展开收缩
const searchInputExpland = ref(false);
const treeRef = ref();

const treeProps = {
  label: "orgName",
  children: "children",
  isLeaf: "leaf",
};

// 查询区域表单数据
const formSearch = reactive({
  account: "",
  name: "",
  employeeNumber: "",
  orgName: "",
  orgCode: "",
  deptName: "",
  deptCode: "",
  status: "",
});
const state = reactive({
  refresh: true,
  // 表格列配置，大部分属性跟el-table-column配置一样
  columns: [
    // {
    //   field: "accountId",
    //   type: "selection",
    //   align: "center",
    //   width: 55,
    // },
    {
      title: () => t("account.name"),
      field: "name",
      sortable: true,
      resizable: true,
      width: 150,
    },
    {
      title: () => t("account.account"),
      field: "account",
      sortable: true,
      resizable: true,
      tdSlot: "account",
      width: 250,
    },
    {
      title: () => t("account.employeeNumber"),
      field: "employeeNumber",
      sortable: true,
      resizable: true,
      hidden: true,
      width: 180,
    },
    {
      title: () => t("account.orgName"),
      field: "orgName",
      sortable: true,
      resizable: true,
    },
    {
      title: () => t("account.deptName"),
      field: "deptName",
      sortable: true,
      resizable: true,
      hidden: true,
    },
    {
      title: () => t("account.roles"),
      field: "roles",
      sortable: false,
      resizable: true,
      formatter: function (
        row: any,
        column: any,
        cellValue: any,
        index: number
      ) {
        if (cellValue.length > 0) {
          let roles = "";
          cellValue.forEach((r: any) => {
            roles += r.roleName + "、";
          });
          return roles.substring(0, roles.length - 1);
        }
        return "";
      },
    },
    {
      title: () => t("account.status"),
      field: "status",
      tdSlot: "status",
      sortable: true,
      resizable: true,
      width: 100,
    },
    {
      title: () => t("common.operateButton"),
      field: "opId",
      tdSlot: "operate",
      width: 150,
    },
  ],
  buttons: [
    {
      type: "primary",
      buttonSlot: "button-primary",
    },
  ],
  row: null,
});

// 加载数据
const handleLoadGrid = async (params: any) => {
  // params 是从表格组件接收的，包含分页和搜索字段，需要补充 query 查询条件信息
  let query = utils.serializeArray(formSearch);
  params.query = JSON.stringify(query);
  let data = { rows: [], total: 0 };
  await apiAccount
    .queryAccountListing(params)
    .then((response: any) => {
      data = response.data;
    })
    .catch((err: any) => {
      utils.errorNotification(t("common.submitException"), err);
    });

  // 返回数据给表格组件
  return data;
};

// 双击事件
const handleRowDblclick = (row: any, column: any) => {
  // console.log("handleRowDblclick", row, column);
};

// 删除操作事件
const handleDelete = (row: any) => {
  ElMessageBox.confirm(t("account.confirmDelete", { name: row.name }), {
    confirmButtonText: t("common.okButton"),
    cancelButtonText: t("common.cancelButton"),
  })
    .then(() => {
      apiAccount
        .deleteAccount(row.accountId)
        .then((response: any) => {
          if (response.data.code == 200) {
            handleSearch();
            utils.infoNotification(t("account.deleted", { name: row.name }));
          }
        })
        .catch((err: any) => {
          utils.errorNotification(t("common.submitException"), err);
        });
    })
    .catch((err: any) => {});
};

// 打开新增页
const handleAdd = () => {
  editFormRef.value.show();
};
// 打开账号日志
const handleLog = async (row: any) => {
  router.push({
    name: "/admin/account/log/list",
    params: { accountName: row.name },
  });
};
// 打开编辑页
const handleEdit = async (row: any) => {
  editFormRef.value.show(row);
};
// 打开修改密码页面
const handleChangePwd = () => {
  let row = dataGridRef.value.getCurrentRow();
  // console.log("handleChangePwd", row);
  if (row == null) {
    ElMessageBox.alert(t("common.selectRecord"), t("common.info"), {
      confirmButtonText: "OK",
      closeOnClickModal: true,
    }).catch(() => {});
    return;
  }
  changePasswordFormRef.value.show(row);
};
// 新增、编辑页确定按钮回调事件
const onSubmitSuccess = (result: boolean) => {
  handleSearch();
};
// 打开详情页
const handleView = (row: any) => {
  viewFormRef.value.show(row);
};

const handleStateChange = (state: any, row: any) => {
  // console.log("handleStateChange", state, row.accountId);
  if (row.accountId != undefined) {
    // 避免第一次加载页面触发
    apiAccount
      .changeAccountStatus(row.accountId, state == 1 ? 1 : 0)
      .then((response: any) => {
        if (response.data.code == 200) {
        }
      })
      .catch((err: any) => {
        utils.errorNotification(t("common.submitException"), err);
      });
  }
};

const handleCodeRefresh = () => {
  state.refresh = false;
  setTimeout(() => {
    state.refresh = true;
  }, 10);
};
const lazyLoadNode = async (
  node: Node,
  resolve: (data: OrgTreeNode[]) => void
) => {
  if (node.level === 0) {
    let treeData = await apiOrganization.loadChilds("0");
    return resolve(treeData);
  } else {
    if (node.data.leaf) {
      resolve([]);
    }
    let treeData = await apiOrganization.loadChilds(node.data.orgId);
    return resolve(treeData);
  }
};

const onTreeNodeCurrentChange = (data: OrgTreeNode, node: Node) => {
  // console.log("onTreeNodeCurrentChange", data, node);
  if (data == null) {
    return;
  }
  if (data.category == "UNIT" || data.category == "单位") {
    formSearch.orgCode = data.orgCode;
    formSearch.deptCode = "";
  } else {
    formSearch.orgCode = "";
    formSearch.deptCode = data.orgCode;
  }
  handleSearch();
};
const handleTreeClearSelect = () => {
  treeRef.value.setCurrentKey(null);
  formSearch.orgCode = "";
  formSearch.deptCode = "";
  handleSearch();
};

// 刷新表格
const handleSearch = () => {
  dataGridRef.value.loadGridData();
};
const handleResetFields = () => {
  formSearchRef.value.resetFields();
};
</script>
<style lang="scss" scoped>
.el-card {
  border-radius: 0;
  border: none;
}

.data-grid-search-form {
  margin-bottom: 0;
  padding-bottom: 0;
}
</style>
